local state = {}
state.name = "FIRING INDIRECT"
state.id = 6

if(SERVER) then

  state.startTime = nil

  function state.New()
    return table.Copy(state)
  end

  function state:Run(ag3)
    if(self.startTime == nil) then
      self.startTime = CurTime()
    end
    
    local group = ag3:GetGroup()
    local duration = #group
    
    if(CurTime() - self.startTime >= duration) then
      if(self.beam ~= nil) then      
        self.beam:Remove()
      end
      
      return ag3:SetNextState(ag3.States.Idle)
    end
    
    if(self.beam == nil) then
      self.beam = self:CreateBeam(ag3)
    else
      self.beam:SetEndPos(group.focalPoint)
    end
    
    if(group.beam == nil) then
      group.beam = self:CreateGroupBeam(ag3)
    end
    
    return self
  end
  
  function state:CreateBeam(ag3)
    local beam = ents.Create("energy_beam")

    if(ValidEntity(beam) == false) then
      error("Could not create beam.\n")
    end

    local Start = {}
    Start.Entity = ag3
    Start.offset = ag3:GetEmitterPos() - ag3:GetPos()

    local Damage = {}
    Damage.amount = ag3.Damage.current
    Damage.radius = ag3.Damage.radius

    beam:Setup(ag3, 
               Start, 
               Damage, 
               ag3:GetBeamSpeed(),
               ag3:GetBeamColour())
                   
    beam:Spawn()
    beam:Activate()

    beam:EmitSound(ag3:GetFiringSound(), 100, 100)
    
    return beam
  end
  
  function state:CreateGroupBeam(ag3)
    local beam = ents.Create("energy_beam")

    if(ValidEntity(beam) == false) then
      error("Could not create beam.\n")
    end

    local beamVector = Vector(0,0,0)
    
    local BeamDamage = {}
    BeamDamage.amount = 0
    BeamDamage.radius = 0
    
    local group = ag3:GetGroup()
    
    for _, groupMember in ipairs(group) do
      beamVector = beamVector + groupMember:GetForward()
      BeamDamage.amount = BeamDamage.amount + groupMember.Damage.current
      BeamDamage.radius = BeamDamage.radius + groupMember.Damage.radius
    end
    
    beamVector = (beamVector / #group):GetNormal()
    BeamDamage.radius = BeamDamage.radius / #group
    
    local Start = {}
    Start.Entity = ag3
    Start.offset = group.focalPoint - ag3:GetEmitterPos()
    Start.angle = (beamVector - ag3:GetForward()):Angle()

    beam:Setup(ag3, 
               Start, 
               BeamDamage, 
               ag3:GetBeamSpeed(),
               ag3:GetBeamColour())
    
    beam:Spawn()
    beam:Activate()
    
    return beam
  end
  
end

ENT.States.FiringIndirect = state
